<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          size="small"
          icon="el-icon-view"
          plain
          @click="handleExam(scope.row)">
          开始考试
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="在线考试" append-to-body :visible.sync="tmylBox" width="50%" :before-close="handleClose">

      <el-form ref="personForm" :model="person" :rules="rules" label-width="80px">
            <span v-if="controlForm.pxlb===2">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="培训类别" prop="pxlb">
                  <el-select size="small" placeholder="培训类别" v-model="person.pxlb">
                    <el-option
                      v-for="(item, index) in getWlpxlb"
                      :key="index"
                      :label="item.dictValue"
                      :value="item.dictKey"
                    >
                  </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                  <el-form-item label="姓名" prop="xm">
                    <el-input size="small" placeholder="请输入姓名" v-model="person.xm"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-form-item label="身份证号" prop="sfzh">
                    <el-input size="small" placeholder="请输入身份证号" v-model="person.sfzh"></el-input>
                  </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="ssdw">
                  <el-input size="small" placeholder="所属单位" v-model="person.ssdw"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="人员职位" prop="ryzw">
                  <el-input size="small" placeholder="人员职位" v-model="person.ryzw"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            </span>
      </el-form>
      <span v-if="controlForm.pxlb===1 || controlForm.pxlb===3">
<!--               <el-col :span="12">-->
        <!--                  <el-input size="small" placeholder="请输入姓名" v-model="person.xm"></el-input>-->
        <!--               </el-col>-->
            </span>


      <el-form v-model="controlForm" label-width="120px" v-for="(item,index) in questions" :key="index" :val="item">
        <el-row :gutter="24">
          <el-col :span="24">
              <span v-if="item.stlx===1">
                <el-row>
                <el-col>{{index+1}}.{{item.stnr}}(单选)</el-col>
              </el-row>
								<el-row>
									<el-col>
										<div>
<!--                      chooseAnswers[index]-->
                        <el-radio-group v-model="chooseAnswers[index]">
                          <el-radio label="A" border>
														<span class="answerstyle">A.</span>
														{{item.xxA}}
													</el-radio>
                          <el-radio label="B" border>
														<span class="answerstyle">B.</span>
														{{item.xxB}}
													</el-radio>
                          <el-radio label="C" border>
														<span class="answerstyle">C.</span>
														{{item.xxC}}
													</el-radio>
                          <el-radio label="D" border>
														<span class="answerstyle">D.</span>
														{{item.xxD}}
													</el-radio>
                      </el-radio-group>
										</div>
									</el-col>
								</el-row>
							</span>
            <span v-if="item.stlx===2">
                <el-row>
                  <el-col>{{index+1}}.{{item.stnr}}(多选)</el-col>
                </el-row>
								<el-row>
									<el-col>
										<div>
                      <el-checkbox-group
                        v-model="chooseAnswers[index]"
                      >
                <el-checkbox label="A">{{ item.xxA }}</el-checkbox>
                <el-checkbox label="B">{{ item.xxB }}</el-checkbox>
                <el-checkbox label="C">{{ item.xxC }}</el-checkbox>
                <el-checkbox label="D">{{ item.xxD }}</el-checkbox>
              </el-checkbox-group>

										</div>
									</el-col>
								</el-row>
							</span>
            <span v-else-if="item.stlx===3">
                <el-row>
                  <el-col>{{index+1}}.{{item.stnr}}(填空)</el-col>
                </el-row>
								<el-row>
                  <el-col>
										<div>
                    <avue-input v-model="chooseAnswers[index]" placeholder="请输入答案，例“唐朝，李白”"></avue-input>
                    </div>
                    </el-col>
								</el-row>
							</span>
            <span v-else-if="item.stlx===4">
                <el-row>
                  <el-col>{{index+1}}.{{item.stnr}}(判断)</el-col>
                </el-row>
								<el-row>
                  <el-radio-group v-model="chooseAnswers[index]">
                    <el-radio label="1">正确</el-radio>
                    <el-radio label="2">错误</el-radio>
                  </el-radio-group>
								</el-row>

							</span>
          </el-col>
        </el-row>
      </el-form>


      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closetmyl">提交试卷</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {
    getList,
    getDetail,
    add,
    update,
    remove,
    getQusetion,
    addQuertion,
    getst,
    getKcmc, getXxsc
  } from "@/api/jypx/edupaper/paper";
  import {mapGetters} from "vuex";
  import {getWlpxlb} from "../../../api/jypx/eduOnline/exam";
  import {validateIC} from "../../../api/jypx/educourseware/validate";

  export default {
    data() {
      return {
        person: {
          pxlb: "",
          xm: "",
          sfzh: "",
          ssdw: "",
          ryzw: ""
        },
        rules: {
          pxlb: [{required: true, message: '请填写培训类别', trigger: 'blur'}],
          xm: [{required: true, message: '请填写姓名', trigger: 'blur'}],
          sfzh: [{required: true, validator:validateIC, trigger: 'blur'}],
          ssdw: [{required: true, message: '请填写所属单位', trigger: 'blur'}],
          ryzw: [{required: true, message: '请填写人员职位', trigger: 'blur'}]
        },
        chooseAnswers: [],
        kcmc: "",
        questions: [],
        tmylBox: false,
        rows: {},
        courseId: "",
        //出卷弹窗
        cjBox: false,
        tmBox: false,
        controlForm: {
          dxxl: "",
          dxfz: "",
          dxNum: "",
          dxScore: "",
          pdsl: "",
          pdfz: "",
          tksl: "",
          tkfz: ""
        },
        controlRules: {
          dxxl: [{required: false, message: '请输入单选数量', trigger: 'blur'}],
          dxNum: [{required: false, message: '请输入多选数量', trigger: 'blur'}],
          pdsl: [{required: false, message: '请输入判断数量', trigger: 'blur'}],
          tksl: [{required: false, message: '请输入填空数量', trigger: 'blur'}],
        },
        dialogQuestion: false,
        questionQuery: {},
        questionLoading: true,
        questionPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        questionSelectionList: [],
        questionOption: {
          calcHeight: 30,
          tip: true,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menu: false,
          addBtn: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "试题科目",
              prop: "courseId",
              align: "center",
              row: false,
              search: true,
              slot: false,
              type: "select",
              dicUrl: "/api/eduCourse/course/getCourseKcmc",
              props: {
                label: "kcmc",
                value: "id",
              },
            },
            {
              label: "试题类型",
              prop: "stlx",
              search: true,
              type: "select",
              align: "center",
              dataType: "number",
              dicUrl: "/api/blade-system/dict/dictionary?code=stbh",
              props: {
                label: "dictValue",
                value: "dictKey"
              }
            },
            {
              label: "试题内容",
              prop: "stnr",
              align: "center",
            },
            {
              label: "A",
              prop: "xxA",
              align: "center",
            },
            {
              label: "B",
              prop: "xxB",
              align: "center",
            },
            {
              label: "C",
              prop: "xxC",
              align: "center",
            },
            {
              label: "D",
              prop: "xxD",
              align: "center",
            },
          ]
        },
        questionData: [],
        // questionTags: [],
        questionTagsErr: false,
        selectQuestion: {},

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          addBtn:false,
          viewBtn: false,
          delBtn: false,
          editBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "培训类别",
              prop: "pxlb",
              type: "select",
              search: true,
              align: "center",
              dataType: "number",
              cascaderIndex:0,
              cascaderItem: ['courseId'],
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pxlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              }
            },
            {
              label: "试题科目",
              prop: "courseId",
              align: "center",
              row: false,
              search: true,
              slot: false,
              type: "select",
              cascaderIndex:0,
              dicUrl: "/api/eduCourse/course/getCourseKcmc?code={{key}}",
              props: {
                label: "kcmc",
                value: "id",
              },
              rules: [{
                required: true,
                message: "试题科目",
                trigger: "blur",
              }]
            },
            {
              label: "单选数量",
              prop: "dxxl",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "单选分数",
              prop: "dxfz",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "多选数量",
              prop: "dxNum",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "多选分数",
              prop: "dxScore",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "填空数量",
              prop: "tksl",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "填空分数",
              prop: "tkfz",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "判断数量",
              prop: "pdsl",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "判断分数",
              prop: "pdfz",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "及格分数线",
              prop: "jgfsx",
              align: "center",
              width: "90px",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "添加题目",
              prop: "ids",
              align: "center",
              hide: true,
              viewDisplay: false,
              addDisplay: false,
              editDisplay: false,
              formslot: true,
              labelslot: true
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "修改用户",
              prop: "updateUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "修改时间",
              prop: "updateTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
          ]
        },
        data: [],
        // examrecordId:""
        examrecordVO: {},
        getWlpxlb: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.paper_add, false),
          viewBtn: this.vaildData(this.permission.paper_view, false),
          delBtn: this.vaildData(this.permission.paper_delete, false),
          editBtn: this.vaildData(this.permission.paper_edit, false),
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      qids() {
        let qids = [];
        this.questionSelectionList.forEach(ele => {
          qids.push(ele.id);
        });
        return qids.join(",");
      },
      selected_danx: function () {
        let selected = 0;
        for (let i = 0; i < this.questions.length; i++) {
          if (this.questions[i].stlx == 1) {
            selected++;
          }
        }
        return selected + " / " + this.controlForm.dxxl;
      },
      selected_duox: function () {
        let selected = 0;
        for (let i = 0; i < this.questions.length; i++) {
          if (this.questions[i].stlx == 2) {
            selected++;
          }
        }
        return selected + " / " + this.controlForm.dxxl;
      },
      selected_pd: function () {
        let selected = 0;
        for (let i = 0; i < this.questions.length; i++) {
          if (this.questions[i].stlx == 3) {
            selected++;
          }
        }
        return selected + " / " + this.controlForm.dxxl;
      },
      selected_tk: function () {
        let selected = 0;
        for (let i = 0; i < this.questions.length; i++) {
          if (this.questions[i].stlx == 4) {
            selected++;
          }
        }
        return selected + " / " + this.controlForm.dxxl;
      }
    },
    mounted() {
      this.getWlpxlbs();
    },
    methods: {
      //打开在线考试弹窗
      handleExam(row) {
        getXxsc(row.courseId).then(response => {
          let kcxs=response.data.data.kcxs;
          let yxsc=response.data.data.yxsc;
          if(yxsc/kcxs>0.8){
            this.$confirm("准备好开始考试吗?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                this.tmylBox = true
                axios({
                  method: 'post',
                  url: '/api/eduExamRecord/examrecord/save', // 后台接口
                }).then(res => {
                  this.examrecordVO.examrecordId = res.data.data.id;
                  // this.examrecordVO.ksrName =res.data.data.ksrName;
                  // this.examrecordVO.ksrCard =res.data.data.ksrCard;
                  // this.examrecordVO.ksrId =res.data.data.ksrId;
                  this.chooseAnswers = [];
                  this.person={
                    pxlb: "",
                    xm: "",
                    sfzh: "",
                    ssdw: "",
                    ryzw: ""
                  };

                  this.questions = [];
                  getst(row.id).then(res => {
                    this.form = res.data.data;
                    this.form.questions.forEach((item, index) => {
                      this.questions.push(item);
                      // todo
                      this.chooseAnswers.push([]);
                      // if (item.stlx == 2) {
                      //   this.chooseAnswers[index] = [];
                      // }
                    });
                  });

                  getDetail(row.id).then(response => {
                    this.controlForm = response.data.data;
                  });
                  getKcmc(row.courseId).then(response => {
                    this.kcmc = response.data.data.kcmc;
                  });
                });
              })
              .catch(() => {
              });
          }else if(yxsc/kcxs<0.8){
            this.$message({
              type: "warning",
              message: "您的学时不满80%，请继续学习!"
            });
          }
        });
      },
      //关闭考试弹窗
      handleClose(done) {
        this.$confirm('确认退出考试？')
          .then(() => {
            done();
          })
          .catch(() => {
          });
      },
      // 获取外来培训类别
      getWlpxlbs() {
        getWlpxlb()
          .then(res => {
            this.getWlpxlb = res.data.data;
          })
          .then(() => {
            this.onLoad(this.page);
          });
      },

      //提交试卷
      closetmyl() {
        let obj = {};
        let examRecordArr = [];
        for (let i = 0; i < this.questions.length; i++) {
          let examRecord = {};
          examRecord.questionId = this.questions[i].id;
          if (this.questions[i].stlx == 2) {
            examRecord.xx = this.chooseAnswers[i].join(",");
          } else {
            if(this.chooseAnswers[i].length==0){
              examRecord.xx="";
            }else examRecord.xx = this.chooseAnswers[i];

          }
          examRecordArr.push(examRecord);
        }
        obj.examRecordDetail = examRecordArr;
        obj.paperId = this.controlForm.id;
        obj.wlpxlb = this.person.pxlb;
        obj.ksrName = this.person.xm;
        obj.ksrCard = this.person.sfzh;
        obj.deptName = this.person.ssdw;
        obj.ryzw = this.person.ryzw;
        obj.id = this.examrecordVO.examrecordId;
        // obj.ksrName=this.examrecordVO.ksrName;
        // obj.ksrId=this.examrecordVO.ksrId;
        // obj.ksrCard=this.examrecordVO.ksrCard;
        console.log(obj)

        this.$refs['personForm'].validate(valid => {
          if (valid) {
            this.$confirm("确定提交考卷吗?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                axios({
                  method: 'post',
                  url: '/api/eduExamRecord/examrecord/update', // 后台接口
                  data: obj
                }).then(res=> {
                  this.tmylBox = false
                  this.$message({
                    type: "success",
                    message: "提交成功!"
                  });
                })
              })
          }
        })
      },
      //打开试题弹窗
      tjtm() {
        this.tmBox = true
        this.questionOnLoad(this.questionPage);
      },
      //关闭试题弹窗
      closetm() {
        this.tmBox = false
        this.questionPage.currentPage = 1;
        this.questionSelectionClear();
      },
      //试题获取表格数据
      questionOnLoad(page, params = {}) {
        this.questionLoading = true;
        getQusetion(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.questionPage.total = data.total;
          this.questionData = data.records;
          this.questionLoading = false;
          if (this.selectQuestion !== undefined && JSON.stringify(this.selectQuestion) !== "{}" && this.questions.length !== 0) {
            this.$nextTick(() => {
              this.questionData.forEach(row => {
                if (this.selectQuestion[row.id] !== undefined) {
                  this.$refs.questionCrud.toggleRowSelection(row, true);
                }
              })
            })
          }
        });
      },
      // 试题清空勾选
      questionSelectionClear() {
        this.questionSelectionList = [];
        this.$refs.questionCrud.toggleSelection();
      },
      // 试题搜索条件改变事件
      questionSearchChange(params, done) {
        this.questionQuery = params;
        this.questionPage.currentPage = 1;
        this.questionOnLoad(this.questionPage, params);
        done();
      },
      // 试题清空搜索条件
      questionSearchReset() {
        this.questionQuery = {};
        this.questionOnLoad(this.questionPage);
      },
      // 试题勾选
      questionSelectionChange(list) {
        this.questionSelectionList = list;
      },
      // 试题勾换页数
      questionCurrentChange(currentPage) {
        var pageSelectIds = [];
        var pageAllIds = [];
        this.questionSelectionList.forEach(item => {
          this.selectQuestion[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.questionData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for (var id in this.selectQuestion) {
          if (pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectQuestion[id];
          }
        }
        this.questionPage.currentPage = currentPage;
        this.questionOnLoad(this.questionPage);
      },
      // 试题勾换每页显示数量
      questionSizeChange(pageSize) {
        this.questionPage.pageSize = pageSize;
        this.questionOnLoad(this.questionPage);
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.dcsTagsErr = false;
        this.dcsTags = [];
        this.selectDcs = {};
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        this.query.pxlb=1;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss">
</style>
